package com.eliza.kotlin.design.creation.factory.config_factory

import java.util.*


/*-*- coding:utf-8 -*-
 * @Author  : debi
 * @Time    : 6/5/22
 * @Software: IntelliJ IDEA
 */
object CoffeeFactory {
    //加载配置文件，获取配置文件中配置的全类名，并创建该类的对象进行存储
    //1,定义容器对象存储咖啡对象
    private val map = HashMap<String, Coffee>()

    init {

        //2.1 创建Properties对象
        val p = Properties()
        //2.2 调用p对象中的load方法进行配置文件的加载
        val inputStream = CoffeeFactory::class.java.classLoader.getResourceAsStream("bean.properties")
        try {
            p.load(inputStream)
            //从p集合中获取全类名并创建对象
            val keys: Set<Any> = p.keys
            for (key in keys) {
                val className = p.getProperty(key as String)
                //通过反射技术创建对象
                val clazz = Class.forName(className)
                val coffee = clazz.newInstance() as Coffee
                //将名称和对象存储到容器中
                map[key] = coffee
            }
        } catch (e: Exception) {
            e.printStackTrace()

        }
    }
    //根据名称获取对象
    fun createCoffee(name: String): Coffee? {
        return map[name]
    }

}